package org.example.multiThreading.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 生产者消费者问题
 */
public class Demo7 {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        //创建阻塞队列
        ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
        //创建生产者
        Producer producer = new Producer(queue);
        //创建消费者
        Consumer consumer = new Consumer(queue);
        //放入线程池
        service.execute(producer);
        service.execute(consumer);
        //关闭线程池
        service.shutdown();
    }
}

class Producer implements Runnable{

    ArrayBlockingQueue<Integer> queue;

    public Producer(ArrayBlockingQueue<Integer> queue){
        this.queue=queue;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 30; i++) {
                queue.put(i);
                System.out.println("生产了一个产品,id为:"+i);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class Consumer implements Runnable{
    ArrayBlockingQueue<Integer> queue;
    public Consumer(ArrayBlockingQueue<Integer> queue){
        this.queue=queue;
    }
    @Override
    public void run() {
        for(int i=1;i<=30;i++) {
            try {
                queue.take();
                System.out.println("消费者消费了一个产品，产品ID：" + i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}